package com.ruiyi.adrobot.service.robotinfo.impl;

import com.ruiyi.adrobot.beans.Robot;

import com.ruiyi.adrobot.beans.common.MongoPageRequest;
import com.ruiyi.adrobot.beans.socket.Heart;
import com.ruiyi.adrobot.mongo.robot.RobotRepository;
import com.ruiyi.adrobot.service.robotinfo.RobotService;
import com.ruiyi.adrobot.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.List;

/**
 * Created by Lenovo on 2017/5/8.
 */
@Service
class RobotServiceImpl implements RobotService {
    @Autowired
    private RobotRepository robotRepository;

    @Override
    public void add(Robot robotInfo) {
        robotInfo.setCreateDate(DateUtil.getCurrentTime());
        robotInfo.setOnline(true); // 添加時在綫狀態都為true
        robotRepository.insert(robotInfo);
    }

    @Override
    public Robot findBySimCode(String simCode) {
        return robotRepository.findBySimCode(simCode);
    }

    @Override
    public void saveOrUpdate(Robot robotInfo) {
        robotInfo.setUpdateDate(DateUtil.getCurrentTime());
        robotRepository.save(robotInfo);
    }

    @Override
    public Page<Robot> getListByPage(MongoPageRequest mongoPageRequest, Boolean online) {
        List<Robot> list = robotRepository.findByOnline(online, mongoPageRequest);
        return new PageImpl<Robot>(list, mongoPageRequest, list.size());
    }

    @Override
    public void updateRobotStatus(Heart heart) {
        robotRepository.updateRobotStatus(heart);
    }


    @PreDestroy
    private void destroy() {
        robotRepository.updateOnlineAndBusyFalse();
    }

}
